package arch.dao.impl.user;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import arch.dao.impl.user.mapper.UserMapper;
import arch.dao.user.UserDao;
import arch.domain.user.User;
/**
 * 
 * @author ZhaoWangLong Sep 3, 2012
 *
 */
@Repository("userDao")
public class UserImpl implements UserDao {
	@Resource private JdbcTemplate jdbcTemplate;
	private final Logger logger = Logger.getLogger(UserImpl.class);
	
	public Integer queryCount(String sql, Object... objects) {
		return this.jdbcTemplate.queryForInt(sql, objects);
	}

	@SuppressWarnings("unchecked")
	public List<User> queryList(String sql, boolean defaultDept,Object... objects) {
		logger.debug("SQL > "+sql);
		return this.jdbcTemplate.query(sql, objects, new UserMapper(defaultDept));
	}

	public User find(Serializable primaryKey) {
		String sql = "select USER_ID, USER_NAME, PASSWORD, IS_LOCK, ERROR_COUNT,  "+
		 " DEFAULT_LOGIN_DEPT, CREATE_TIME, LAST_UPDATE_TIME, " +
		 " LAST_UPDATE_PASSWD_TIME from ID_USER  where USER_ID = ? ";
		try {
			return (User)this.jdbcTemplate.queryForObject(sql, new Object[]{primaryKey},new UserMapper());
		}catch (EmptyResultDataAccessException e) {
			return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}

	public void merge(User entity) {
		String sql = "update ID_USER set USER_NAME=? , IS_LOCK=?, ERROR_COUNT=?," +
				"DEFAULT_LOGIN_DEPT = ?,LAST_UPDATE_TIME=? where USER_ID = ?";
		
		this.jdbcTemplate.update(sql,new Object[]{
				entity.getUserName(),
				entity.isLock()?"1":"0",
				entity.getErrorCount(),
				entity.getDefaultLoginDept() == null ? null: entity.getDefaultLoginDept().getDeptId(),
				entity.getLastUpdateTime(),
				entity.getUserId()
		});
	}

	public void persist(User entity) {
		String sql = "insert into ID_USER (USER_ID, USER_NAME, PASSWORD, IS_LOCK, ERROR_COUNT," +
				" DEFAULT_LOGIN_DEPT, CREATE_TIME, LAST_UPDATE_TIME, " + 
				" LAST_UPDATE_PASSWD_TIME ) values (?,?,?,?,?,?,?,?,?)";
		this.jdbcTemplate.update(sql,new Object[]{
				entity.getUserId(),
				entity.getUserName(),
				entity.getPassword(),
				entity.isLock()?"1":"0",
				entity.getErrorCount(),
				entity.getDefaultLoginDept() == null ? null: entity.getDefaultLoginDept().getDeptId(),
				entity.getCreateTime(),
				entity.getLastUpdateTime(),
				entity.getLastUpdatePasswdTime()
		});
	}

	public void remove(Serializable primaryKey) {
		String sql = "delete from ID_USER where USER_ID = ? ";
		this.jdbcTemplate.update(sql,new Object[]{primaryKey});
	}

	public void update(String sql, Object... objects) {
		this.jdbcTemplate.update(sql,objects);
	}
}
